package gc3d.servlet;

import java.io.*;
import java.util.zip.*;

public class Decompress {
	final int BUFFER = 2048;
	
	public void decompressFile(File fArchive){
		String filename = fArchive.getName();
		filename = "test2.fd.zip";
		String extension = filename.substring(filename.lastIndexOf('.'));
		
		// now select the proper function to extract
		if(extension.equals(".zip")){
			// .zip extension
			unzip(fArchive.getAbsolutePath());
		} else if(extension.equals(".pov")) {
			// . pov
			//Do nothing, just keep it...
		} else {
			// the case where the extension is not recognized.
			System.out.println("Wrong fileformat: *"+extension+" files are not supported.");
		}
		
	}
	
	public void unzip(String sFilename) {
		try {
			// the location of the archive. It can be presented in a form like:
			// C:\folder\subfolder\archive.zip. That's why we first replace all backslashed
			// with slashes. Afterwards, we take the substring till the last slash. This is the path!
			sFilename = sFilename.replace('\\', '/');
			String sOutputFolder = new String(sFilename.substring(0, sFilename.lastIndexOf('/')+1));
			System.out.println( sOutputFolder );
			BufferedOutputStream dest = null;
			FileInputStream fis = new FileInputStream(sFilename);
			ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
			
			ZipEntry entry;
			while((entry = zis.getNextEntry()) != null) {
				System.out.println("Extracting: " +entry);
				int count;
				byte data[] = new byte[BUFFER];
				
				// write the files to the disk
				FileOutputStream fos = new FileOutputStream(sOutputFolder+entry.getName());
				dest = new BufferedOutputStream(fos, BUFFER);
				while ((count = zis.read(data, 0, BUFFER)) != -1) {
					dest.write(data, 0, count);
				}
				
				dest.flush();
				dest.close();
			}
			zis.close();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
}